<template>
	<view class="binding-every">
		<view class="binding-content">
			<!-- 标题 -->
			<view class="binding-title">
				<text>{{ getTitle }}</text>
			</view>

			<!-- 用户名修改界面 -->
			<view class="binding-form" v-if="bindingStore.bindingType === 'username'">
				<view class="form-item">
					<input type="text" class="form-input" placeholder="请输入新的用户名" placeholder-class="placeholder"
						v-model="bindingStore.userInfo.name" />
				</view>
			</view>

			<!-- 手机号修改界面 -->
			<view class="binding-form" v-if="bindingStore.bindingType === 'phone'">
				<view class="form-item">
					<input type="text" class="form-input" placeholder="请输入新的手机号" placeholder-class="placeholder"
						v-model="phone" />
				</view>
				<view class="form-item code-item">
					<input type="text" class="form-input code-input" placeholder="请输入验证码"
						placeholder-class="placeholder" v-model="phoneCode" />
					<button class="code-btn" @tap="sendPhoneCode" :disabled="phoneCodeCountdown < 60">
						{{ phoneCodeCountdown < 60 ? `${phoneCodeCountdown}秒后重发` : '获取验证码' }}
					</button>
				</view>
			</view>

			<!-- 微信绑定界面 -->
			<view class="binding-form" v-if="bindingStore.bindingType === 'weixin'">
				<view class="binding-info">
					<text class="binding-tips">点击下方按钮，获取微信授权信息进行绑定</text>
				</view>
				<view class="binding-wx-btn">
					<button class="wx-btn" @click="weixinLogin">获取微信信息</button>
				</view>
				<view class="binding-result" v-if="wxBindResult">
					<text class="binding-success">{{wxBindResult}}</text>
				</view>
			</view>

			<!-- 邮箱绑定界面 -->
			<!-- <view class="binding-form" v-if="bindingStore.bindingType === 'email'">
				<view class="form-item">
					<input type="text" class="form-input" placeholder="请输入邮箱" placeholder-class="placeholder"
						v-model="email" />
				</view>
				<view class="form-item code-item">
					<input type="text" class="form-input code-input" placeholder="请输入验证码"
						placeholder-class="placeholder" v-model="emailCode" />
					<button class="code-btn" @tap="sendEmailCode">获取验证码</button>
				</view>
			</view> -->

			<!-- 生日绑定界面 -->
			<view class="binding-form" v-if="bindingStore.bindingType === 'birthday'">
				<view class="form-item">
					<picker mode="date" :value="bindingStore.userInfo.birthday" start="1900-01-01" end="2023-12-31"
						@change="birthdayChange" class="date-picker">
						<view class="picker-view">
							<text v-if="bindingStore.userInfo.birthday">{{ bindingStore.userInfo.birthday }}</text>
							<text v-else class="placeholder">请选择您的生日</text>
						</view>
					</picker>
				</view>
			</view>

			<!-- 底部按钮 -->
			<view class="binding-buttons">
				<button class="cancel-btn" @tap="closeBinding">取消</button>
				<button class="confirm-btn" @tap="confirmBinding">确定</button>
			</view>
		</view>
	</view>
</template>

<script>
	import bindingStore from '../../store/binding.js';
	import {
		UserModify,
		sendChangePhoneCode,
		ChangePhone
	} from '../../api/userApi.js';
import { code } from '@dcloudio/vue-cli-plugin-uni/packages/postcss/tags.js';

	export default {
		data() {
			return {
				phoneCode:'',
				phone:'',
				// email:'',
				bindingStore: bindingStore,
				// emailCode: '',
				birthday: '',
				// wxBindResult: '',
				platform: '', // 添加平台信息
				phoneCodeCountdown: 60, // 手机验证码倒计时
				phoneCodeTimer: null // 手机验证码定时器
			}
		},
		onLoad() {
			// 获取当前运行平台
			this.platform = uni.getSystemInfoSync().platform;
			console.log('当前运行平台:', this.platform);
		},
		computed: {
			getTitle() {
				switch (this.bindingStore.bindingType) {
					case 'username':
						return "修改用户名";
					case 'phone':
						return "修改手机号";
					case 'weixin':
						return '设置微信';
					// case 'email':
					// 	return '设置邮箱';
					case 'birthday':
						return '设置生日';
					default:
						return '绑定信息';
				}
			}
		},
		methods: {
			sendPhoneCode(){
				if (!this.phone) {
					uni.showToast({
						title: '请先输入手机号',
						icon: 'none'
					});
					return;
				}
				
				// 手机号格式验证
				if (!/^\d{11}$/.test(this.phone)) {
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					});
					return;
				}
				
				// 如果倒计时不是60秒，说明正在倒计时中，不允许再次发送
				if (this.phoneCodeCountdown < 60) {
					return;
				}
				
				uni.showToast({
					title: '验证码发送中...',
					icon: 'none'
				});
				
				sendChangePhoneCode(this.phone);
				
				// 开始倒计时
				this.phoneCodeCountdown = 60;
				this.phoneCodeTimer = setInterval(() => {
					this.phoneCodeCountdown--;
					if (this.phoneCodeCountdown <= 0) {
						clearInterval(this.phoneCodeTimer);
						this.phoneCodeCountdown = 60;
					}
				}, 1000);
				
				setTimeout(() => {
					uni.showToast({
						title: '验证码已发送',
						icon: 'success'
					});
				}, 1000);
			},
			getUserInfo() {
				return new Promise((resolve, reject) => {
					uni.getUserProfile({
						lang: 'zh_CN',
						desc: '用户登录', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，
						success: (res) => {
							console.log(res, 'resss')
							resolve(res.userInfo)
						},
						fail: (err) => {
							console.log('获取用户信息失败:', err)
							uni.showModal({
								title: '获取用户信息失败',
								content: JSON.stringify(err),
								showCancel: false
							})
							reject(err)
						}
					})
				})
			},

			getLogin() {
				return new Promise((resolve, reject) => {
					uni.login({
						provider: 'weixin',
						success(res) {
							console.log('微信登录成功:', res)
							resolve(res)
						},
						fail: (err) => {
							console.log('微信登录失败:', err)
							uni.showModal({
								title: '微信登录失败',
								content: JSON.stringify(err),
								showCancel: false
							})
							reject(err)
						}
					})
				})
			},

			// weixinLogin() {
			// 	let that = this;
			// 	uni.showLoading({
			// 		title: '获取中...'
			// 	});

			// 	// 检查是否安装微信
			// 	uni.getSystemInfo({
			// 		success: function(sysInfo) {
			// 			console.log('系统信息:', sysInfo);
			// 			uni.showModal({
			// 				title: '系统信息',
			// 				content: `平台: ${sysInfo.platform}\n品牌: ${sysInfo.brand}\n型号: ${sysInfo.model}\nSDK版本: ${sysInfo.SDKVersion}`,
			// 				showCancel: false
			// 			});
			// 		}
			// 	});

			// 	// 检查当前环境是否支持微信登录
			// 	uni.getProvider({
			// 		service: 'oauth',
			// 		success: function(res) {
			// 			console.log('可用的服务提供商:', res.provider);
			// 			uni.showModal({
			// 				title: '可用的服务提供商',
			// 				content: JSON.stringify(res.provider),
			// 				showCancel: false
			// 			});

			// 			if (res.provider.indexOf('weixin') !== -1) {
			// 				// 先获取登录code
			// 				that.getLogin().then(loginRes => {
			// 					console.log('微信登录成功:', loginRes);
			// 					const code = loginRes.code;
								
			// 					uni.showModal({
			// 						title: '获取code成功',
			// 						content: `code: ${code}`,
			// 						showCancel: false
			// 					});

			// 					// 获取用户信息
			// 					that.getUserInfo().then(userInfo => {
			// 						console.log('获取用户信息成功:', userInfo);

			// 						// 整合数据
			// 						const bindData = {
			// 							code: code,
			// 							userInfo: userInfo
			// 						};

			// 						// 显示整合的数据
			// 						uni.showModal({
			// 							title: '绑定数据',
			// 							content: JSON.stringify(bindData),
			// 							showCancel: false
			// 						});

			// 						// 这里应该发送到后端进行处理
			// 						// 模拟发送到后端
			// 						setTimeout(() => {
			// 							that.wxBindResult = `绑定成功! 微信昵称: ${userInfo.nickName}`;
			// 							uni.hideLoading();
			// 						}, 1000);
			// 					}).catch(err => {
			// 						uni.hideLoading();
			// 						uni.showToast({
			// 							title: '获取用户信息失败',
			// 							icon: 'none'
			// 						});
			// 					});
			// 				}).catch(err => {
			// 					uni.hideLoading();
			// 					uni.showToast({
			// 						title: '微信登录失败',
			// 						icon: 'none'
			// 					});
			// 				});
			// 			} else {
			// 				uni.hideLoading();
							
			// 				// 检查是否在微信小程序环境中
			// 				// #ifdef MP-WEIXIN
			// 				uni.showModal({
			// 					title: '环境检测',
			// 					content: '当前在微信小程序环境中，但未检测到微信登录服务',
			// 					showCancel: false
			// 				});
			// 				// #endif
							
			// 				// 检查是否在APP环境中
			// 				// #ifdef APP-PLUS
			// 				uni.showModal({
			// 					title: '环境检测',
			// 					content: '当前在APP环境中，但未检测到微信登录服务，请检查是否集成了微信SDK',
			// 					showCancel: false
			// 				});
			// 				// #endif
							
			// 				// 检查是否在H5环境中
			// 				// #ifdef H5
			// 				uni.showModal({
			// 					title: '环境检测',
			// 					content: 'H5环境不支持直接调用微信登录，需要使用微信网页授权',
			// 					showCancel: false
			// 				});
			// 				// #endif
							
			// 				uni.showToast({
			// 					title: '当前环境不支持微信登录',
			// 					icon: 'none'
			// 				});
			// 			}
			// 		},
			// 		fail: function(err) {
			// 			console.log('获取服务提供商失败:', err);
			// 			uni.hideLoading();
			// 			uni.showModal({
			// 				title: '获取服务提供商失败',
			// 				content: JSON.stringify(err),
			// 				showCancel: false
			// 			});
			// 		}
			// 	});
			// },
			// 关闭绑定界面
			closeBinding() {
				this.bindingStore.hideBinding();
				// 清除绑定数据
				// this.email = '';
				// this.emailCode = '';
				this.birthday = '';
				// this.wxBindResult = '';
			},

			// 确认绑定操作
			async confirmBinding() {
				// await uni.showModal({
				// 	title:'userInfo',
				// 	content:JSON.stringify(this.bindingStore.userInfo),
				// 	showCancel:true,
				// 	confirmText:"ok"
				// })
				// 'weixin', 'email', 'birthday', 'username','phone'
				if (this.bindingStore.bindingType == 'phone') {
					//如果code验证成功
					const res = await ChangePhone({
						user:{
							id: this.bindingStore.userInfo.id,
							mobile:this.phone
							// wechatId: this.bindingStore.userInfo.wechatId
							// email: this.bindingStore.userInfo.email
						},
						code:this.phoneCode
					});
					console.log(res.data);
					if(res.data==="success"){
						this.bindingStore.userInfo.mobile=this.phone;
					}
					this.closeBinding();
					return
				}
				// if (this.bindingStore.bindingType == 'email') {
				// 	if(false){
				// 		this.bindingStore.userInfo.email=this.email;
				// 	}
				// 	return
				// }
				// if (this.bindingStore.bindingType == 'weixin') {
				// 	if(false){
				// 		// this.bindingStore.userInfo.wechatId=this.wechatId;
				// 	}
				// 	return
				// }
				const res = await UserModify({
					id: this.bindingStore.userInfo.id,
					nickName: this.bindingStore.userInfo.name,
					birthday: this.bindingStore.userInfo.birthday
					// wechatId: this.bindingStore.userInfo.wechatId
					// email: this.bindingStore.userInfo.email
				});
				// await uni.showModal({
				// 	title:'信息',
				// 	content:JSON.stringify(res),
				// 	showCancel:true,
				// 	confirmText:"ok"
				// })


				// 关闭绑定界面
				this.closeBinding();
			},

			// 发送邮箱验证码
			// sendEmailCode() {
			// 	// 这里的具体实现由用户自己完成
			// 	console.log('发送验证码到邮箱:', this.email);
			// },

			// 生日选择变更
			birthdayChange(e) {
				const dateStr = e.detail.value; // 假设格式为 "yyyy-MM-dd"
				// 补全时间部分（默认00:00:00）
				this.bindingStore.userInfo.birthday = `${dateStr} 00:00:00`;
			}
		},
		// 组件销毁时清除定时器
		beforeDestroy() {
			// 清除手机验证码定时器
			if (this.phoneCodeTimer) {
				clearInterval(this.phoneCodeTimer);
			}
		}
	}
</script>

<style>
	.binding-every {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.7);
		z-index: 999;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.binding-content {
		width: 80%;
		max-width: 600rpx;
		background-color: #ffffff;
		border-radius: 20rpx;
		padding: 40rpx;
		box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.5);
		border: 1rpx solid rgba(255, 106, 0, 0.4);
		color: white;
	}

	.binding-title {
		font-size: 34rpx;
		font-weight: bold;
		text-align: center;
		margin-bottom: 40rpx;
		color: #000000;
	}

	.binding-form {
		margin-bottom: 40rpx;
	}

	.binding-info {
		text-align: center;
		margin-bottom: 30rpx;
	}

	.binding-tips {
		color: rgba(113, 113, 113, 0.8);
		font-size: 28rpx;
		line-height: 1.6;
	}

	.binding-wx-btn {
		display: flex;
		justify-content: center;
		margin: 30rpx 0;
	}

	.wx-btn {
		background: #07c160;
		color: white;
		border-radius: 40rpx;
		width: 80%;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 28rpx;
	}

	.form-item {
		margin-bottom: 30rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.form-input {
		background: rgba(0, 0, 0, 0.1);
		border-radius: 10rpx;
		height: 80rpx;
		padding: 0 20rpx;
		color: #000000;
		width: 100%;
		box-sizing: border-box;
	}

	.placeholder {
		color: rgba(0, 0, 0, 0.5);
	}

	.code-item {
		display: flex;
		justify-content: space-between;
	}

	.code-input {
		width: 60%;
	}

	.code-btn {
		width: 35%;
		height: 80rpx;
		line-height: 80rpx;
		background-color: #007AFF;
		color: #fff;
		font-size: 28rpx;
		border-radius: 0 12rpx 12rpx 0;
		text-align: center;
		border: none;
	}

	.code-btn[disabled] {
		background-color: #a0a0a0;
		color: #e0e0e0;
	}

	.date-picker {
		width: 100%;
	}

	.picker-view {
		background: rgba(0, 0, 0, 0.1);
		border-radius: 10rpx;
		height: 80rpx;
		padding: 0 20rpx;
		color: #000000;
		display: flex;
		align-items: center;
	}

	.binding-buttons {
		display: flex;
		justify-content: space-between;
	}

	.cancel-btn,
	.confirm-btn {
		width: 45%;
		height: 80rpx;
		line-height: 80rpx;
		border-radius: 40rpx;
		font-size: 28rpx;
	}

	.cancel-btn {
		background: rgba(122, 122, 122, 0.1);
		color: rgba(0, 0, 0, 0.8);
	}

	.confirm-btn {
		background: linear-gradient(to right, #FF6A00, #FF4500);
		color: white;
	}

	.binding-result {
		text-align: center;
		margin-top: 30rpx;
	}

	.binding-success {
		color: #07c160;
		font-size: 28rpx;
	}
</style>